<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>创建订单</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="$router.back()">返回</el-button>
      </div>
      <div class="course-info">
        <div>
          <span class="course-name">{{ course.name }}</span>
          <span>x1</span>
        </div>
        <div class="course-price">￥ {{ course.price }}</div>
      </div>
      <!--支付方式-->
      <el-row type="flex" align="middle">
        支付方式：
        <el-radio v-model="payType" :label="pay.alipay" class="f-ac">
          <el-image :src="require('@/assets/pay-type-images/alipay.png')" />
        </el-radio>
      </el-row>
      <!--操作按钮-->
      <el-row type="flex" justify="end">
        <el-button type="primary" @click="handleCreate">创建订单</el-button>
      </el-row>
    </el-card>
    <!--跳转支付宝使用-->
    <div v-show="false" class="payform" />
  </div>
</template>

<script>
import { createByStudent } from '@/api/order'
import { getCourseById } from '@/api/course'

// 支付方式代码
const pay = {
  alipay: 1,
  wechat: 2,
  other: 3
}

export default {
  name: 'Create',
  data() {
    return {
      courseId: undefined,
      course: {},
      payType: 1,
      pay,
      // 加载课程列表
      courseLoading: true
    }
  },
  created() {
    this.courseId = this.$route.query.id
    this.getCourseById()
  },
  methods: {
    getCourseById() {
      getCourseById(this.courseId).then(res => {
        this.course = res.data
      })
    },
    handleCreate() {
      const data = {
        courseId: this.courseId,
        payType: this.payType
      }
      // 创建订单
      createByStudent(data).then(res => {
        this.$notify.success({
          title: '成功',
          message: res.msg,
          duration: 2000
        })
        // 现金支付,跳转订单详情页
        if (data.payType === pay.cash) {
          this.$router.push('/order/info?code=' + res.data)
        } else if (data.payType === pay.alipay) {
          // 支付宝支付
          document.querySelector('.payform').innerHTML = res.data
          this.$nextTick(() => {
            document.forms[0].submit()
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card {
  margin: 20px 0;
}
.course-info {
  margin-bottom: 30px;
  width: 100%;
  border: 1px solid #DBDBDB;
  padding:  20px 10px;
  border-radius: 5px;
  display: flex;
  justify-content: space-between;
  .course-name {
    line-height: 20px;
    font-size: 15px;
    font-weight: bold;
    margin-right: 20px;
  }
  .course-price {
    line-height: 20px;
    font-size: 15px;
    font-weight: bold;
    color: #FF4C4C;
  }
}
.f-ac {
  display: flex;
  align-items: center;
}
.el-image {
  width: 120px;
}
</style>
